package com.neuedu.javase.jdbc.service;

import com.neuedu.javase.jdbc.dao.AccountDao;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-12 13:42
 * 描述 :
 */
public class AccountService {

    private AccountDao accountDao = new AccountDao();
    /**
     * 转账
     * @return
     */
    public boolean transfer(){

        Connection conn = null;
        int count1 = 0;
        int count2 = 0;
        try {
            //创建一个Connection
            conn = accountDao.getConnection();


            conn.setAutoCommit(false); //默认是每条sql单独提交
            //给张三 -50
            String sql1 = "update account set amout = amout - 50 where id = 1";
            count1 = accountDao.update(conn, sql1);

            int result = 10/2; //模拟大量的业务逻辑

            //给李四 +50
            String sql2 = "update account set amout = amout + 50 where id = 2";
            count2 = accountDao.update(conn, sql2);

            //提交事务
            conn.commit();
        } catch (Exception throwables) {
            throwables.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return count1>0 && count2>0;

    }

    public static void main(String[] args) {
        AccountService accountService = new AccountService();
        boolean transfer = accountService.transfer();
        System.out.println("transfer = " + transfer);
    }

}
